package com.template.cms.auth.service;

import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.template.auth.mapper.RoleMapper;
import com.template.auth.mapper.UserRoleMapper;
import com.template.auth.model.Role;
import com.template.auth.model.RoleExample;
import com.template.auth.model.UserRole;
import com.template.auth.model.UserRoleExample;
import com.template.auth.utils.Page;
import com.template.auth.utils.SystemContext;
import com.template.cms.auth.exception.CMSException;
@Service
public class RoleService implements IRoleService {

	@Inject
	private RoleMapper roleMapper;

	@Inject
	private UserRoleMapper userRoleMapper;

	@Override
	public void add(Role role) {
		roleMapper.insertSelective(role);
	}

	@Override
	public void delete(int id) {
		UserRoleExample userRoleExample = new UserRoleExample();
		userRoleExample.createCriteria().andRIdEqualTo(id);
		List<UserRole> userRole = userRoleMapper.selectByExample(userRoleExample);
		if (userRole.size() > 0)
			throw new CMSException("删除的角色中还有用户，不能删除");
		roleMapper.deleteByPrimaryKey(id);
	}

	@Override
	public void update(Role role) {
		roleMapper.updateByPrimaryKeySelective(role);
	}

	@Override
	public Role load(int id) {
		return roleMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<Role> listRole() {
		return roleMapper.selectByExample(new RoleExample());
	}

	@Override
	public void deleteRoleUsers(int rid) {
		UserRoleExample userRoleExample = new UserRoleExample();
		userRoleExample.createCriteria().andRIdEqualTo(rid);
		userRoleMapper.deleteByExample(userRoleExample);
	}

	@Override
	public Page<Role> findRole() {
		Page<Role> page = new Page<Role>(SystemContext.getPageOffset(),SystemContext.getPageSize());
		RoleExample roleExample = new RoleExample();
		page.setTotalRecords(roleMapper.countByExample(roleExample));
		roleExample.setOrderByClause(SystemContext.getSort()+" "+SystemContext.getOrder());
		roleExample.setPage(page);
		page.setPageDatas(roleMapper.selectByExample(roleExample));
		return page;
	}

}
